<template>
  <el-button type="primary" v-per2="['depart-list','post']" @click="doAdd">添加部门</el-button>
  <el-row style="margin-top:20px;">
    <el-table :data="state.tableData" border style="width: 100%" v-loading="state.isLoading"
              v-per2="['depart-list','get']">
      <el-table-column type="selection" width="55" label="选择"/>
      <el-table-column label="序号">
        <template #default="{ $index }">
          {{ $index + 1 }}
        </template>
      </el-table-column>
      <el-table-column sortable prop="classification_title" label="部门分类"/>
      <el-table-column sortable prop="title" label="部门名称"/>
      <el-table-column
          v-if="hasButton([{name:'depart-detail',method:'put'},{name:'depart-detail',method:'delete'}])"
          label="操作">
        <template #default="scope">
          <el-popconfirm

              cancel-button-type="danger"
              confirm-button-text="确定"
              cancel-button-text="取消"
              @confirm="confirmDelete(scope.row)"
              title="确认删除吗?">
            <template #reference>
              <el-button v-per2="['depart-detail','delete']" type="danger" size="small" icon="Delete"
                         class="card-small-btn">删 除
              </el-button>
            </template>
          </el-popconfirm>
          <el-button v-per2="['depart-detail','put']" type="success" size="small" icon="Edit"
                     class="card-small-btn"
                     @click="doEdit(scope.row,scope.$index)">编 辑
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <MinePager v-per2="['depart-list','get']" :pager="state.pager"/>
  </el-row>
  <MineDialog :obj="state.addDialog"></MineDialog>
  <MineDialog :obj="state.editDialog"></MineDialog>
</template>

<script setup>
import {onMounted, reactive, ref} from "vue";
import _axios from "@/plugin/axios.js";
import {ElMessage} from "element-plus";
import MineDialog from "@/components/DialogDouble.vue";
import MinePager from "@/components/MinePager.vue";
import {hasPermission2, hasButton} from "@/stores/permission.js";


const state = reactive({
  isLoading: false,
  tableData: [],
  pager: {
    currentPage: 1,
    totalCount: 0,
    perPageSize: 10,
    handleSizeChange: handleSizeChange,
    handleChangePage: handleChangePage
  },
  editId: -1,
  editIndex: -1,
  addDialog: {
    visible: false,
    title: "添加部门",
    form: {
      title: "",
      classification: [],
    },
    options: {
      classification: []
    },
    errors: {
      title: "",
      classification: "",
    },
    fields: [
      {name: 'title', label: '部门名称', wiget: 'input'},
      {name: 'classification', label: '部门分类', wiget: 'select'},

    ],
    doSubmit: doSubmit
  },
  editDialog: {
    visible: false,
    title: "编辑部门",
    form: {
      title: "",
      classification: [],
    },
    options: {
      classification: []
    },
    errors: {
      title: "",
      classification: "",
    },
    fields: [
      {name: 'title', label: '部门名称', wiget: 'input'},
      {name: 'classification', label: '部门分类', wiget: 'select'},

    ],
    doSubmit: doSubmit
  }
})


onMounted(() => {
  fetchTable(state.pager.currentPage, state.pager.perPageSize)
})

function fetchTable(page, limit) {
  if (hasPermission2("depart-list", "get")) {
    _axios.get("/api/web/depart/", {params: {page: page, page_size: limit}}).then((res) => {
      if (res.data.code === 0) {
        state.tableData = res.data.data.data;
        state.pager.totalCount = res.data.data.totalCount;
        state.pager.perPageSize = res.data.data.perPageSize
      }
    })
  }
}

function fetchClassification() {
  _axios.get('/api/web/depart/classification/').then((res) => {
    if (res.data.code === 0) {
      state.addDialog.options.classification = res.data.data
      state.editDialog.options.classification = res.data.data
    }
  })
}

function handleChangePage(page) {
  state.pager.currentPage = page
  fetchTable(page, state.pager.perPageSize)
}

function handleSizeChange(page_size) {
  state.pager.perPageSize = page_size
  fetchTable(1, page_size)
}

function doAdd() {
  state.addDialog.visible = true
  state.editId = -1
  state.editIndex = -1
  state.addDialog.errors = {}

  state.addDialog.form = {
    title: "",
    classification: undefined
  }
  fetchClassification()
}

function confirmDelete(row) {
  _axios.delete(`/api/web/depart/${row.id}/`).then((res) => {
    if (res.data.code === 0) {
      // state.tableData = state.tableData.filter((item) => {
      //   return row.id !== item.id
      // })
      fetchTable(state.pager.currentPage, state.pager.perPageSize)
      ElMessage.success("删除成功")
    } else {
      ElMessage.error("删除失败")
    }
  })
}

function doEdit(row, index) {
  state.editDialog.errors = {}
  state.editDialog.visible = true
  state.editDialog.title = '编辑部门'
  state.editId = row.id
  state.editIndex = index
  let dict = state.tableData[index]
  state.editDialog.form = {
    title: dict.title,
    classification: dict.classification
  }
  fetchClassification()

}

function doSubmit() {
  if (state.editId > 0) {
    state.editDialog.errors = {}
    _axios.put(`/api/web/depart/${state.editId}/`, state.editDialog.form).then((res) => {
      if (res.data.code === 0) {
        state.tableData[state.editIndex] = res.data.data
        state.editId = -1
        state.editIndex = -1
        state.editDialog.visible = false
      } else if (res.data.code === 2001) {
        for (let key in res.data.detail) {
          state.editDialog.errors[key] = res.data.detail[key][0]
        }
      } else {
        ElMessage.error("编辑失败")
      }
    })
  } else {
    state.addDialog.errors = {}
    _axios.post('/api/web/depart/', state.addDialog.form).then((res) => {
      if (res.data.code === 0) {
        //state.tableData.unshift(res.data.data)
        state.addDialog.form = {
          title: "",
          classification: []
        }
        state.addDialog.visible = false
        fetchTable(state.pager.currentPage, state.pager.perPageSize)
      } else if (res.data.code === 2001) {
        for (let key in res.data.detail) {
          state.addDialog.errors[key] = res.data.detail[key][0]
        }
      } else {
        ElMessage.error("添加失败")
      }
    })
  }
}


</script>

<style scoped>

</style>